﻿using DapperExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WeChatParking.Core.TCPServer;

namespace WeChatParking.Web.Controllers
{
    public class TcpServerController : BaseController
    {
        //
        // GET: /TcpServer/
        static AsyncSocketTCPServer openServer = null;
        static Dictionary<string, SocketList> DicListData = new Dictionary<string, SocketList>();

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Open()
        {
            try
            {
                string ip = Request.Form["ip"];
                if (String.IsNullOrWhiteSpace(ip))
                {
                    return base.Fail("ip不能为空");
                }
                if (String.IsNullOrWhiteSpace(Request.Form["port"]))
                {
                    return Fail("端口不能为空");
                }
                int port = int.Parse(Request.Form["port"]);
                string msg = OpenServer(ip, port);
                return msg.Length > 0 ? base.Fail(msg) : OK();
            }
            catch (Exception ex)
            {
                return Fail(ex.ToString());
            }
        }
        [HttpPost]
        public ActionResult Query()
        {

            var filter = base.GetPageInfo();
            bool asc = filter.asc;
            if (string.IsNullOrWhiteSpace(filter.sort)) filter.sort = "create_time";
            IList<ISort> sort = new List<ISort>
            {
                new Sort{ PropertyName = filter.sort, Ascending = filter.asc}
            };
            using (var db = Repository.DbContext.Create())
            {
                var data = db.GetPageList<Entity.Device>(null, sort, filter);
                foreach (var item in data.DataList)
                {
                    // item.DeviceClient_code   
                    if (DicListData.ContainsKey(item.DeviceClient_code))
                    {
                        if (DicListData[item.DeviceClient_code].time < DateTime.Now.AddMinutes(-2))
                        {
                            item.version = 0;
                            DicListData.Remove(item.DeviceClient_code);
                        }
                        else
                            item.version = 10;
                    }
                    else
                        item.version = 0;
                }
                return base.ToGridJson(data);
            }
        }
        [HttpPost]
        public ActionResult QueryYPay()
        {
            if (openServer == null) return OK();
            string code = "";
            WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
            WeChatParking.Entity.Api.YPay ypay = bll.GetYPay(String.Format(" State=1 "), "create_time");
            if (ypay == null)
            {
                return OK();
            }
            byte[] dataByte = SendDatas.zhuDongYPay(ypay, ref code);
            if (Send(dataByte, code))
            {
                bll.UpdateYPay(ypay.Guid, 2);
            }
            return OK();
        }
        [HttpPost]
        public ActionResult QueryUpinoPay()
        {
            var paySessionList = new WeChatParking.Core.BLL.retry().Get(" status=0 ");
            string request = "";
            if (paySessionList != null && paySessionList.Count > 0)
            {
                foreach (var item in paySessionList)
                {
                    //支付查询
                    if (item.type == 0)
                    {
                        if (item.num <= 5)
                        {
                            if (item.time.AddSeconds(10) <= DateTime.Now)
                            {
                                new WeChatParking.Core.Payment.UnionPay.ActiveAct().payStatus(item.order_id, out request);
                                new WeChatParking.Core.BLL.retry().Update(item);
                            }
                        }
                        //else if (item.num > 5 && item.num < 8)
                        //{
                        //    if (item.time.AddMinutes(1) <= DateTime.Now)
                        //    {
                        //        new WeChatParking.Core.Payment.UnionPay.ActiveAct().payStatus(item.order_id, out request);
                        //        new WeChatParking.Core.BLL.retry().Update(item);
                        //    }
                        //}
                    }//退款请求
                    else if (item.type == 1)
                    {
                        if (item.num <= 3)
                        {
                            if (item.time.AddMinutes(1) <= DateTime.Now)
                            {
                                var ord = new WeChatParking.Core.BLL.PrepaidOrder().GetOrder(item.order_id);
                                item.time = DateTime.Now;
                                new WeChatParking.Core.BLL.retry().Update(item);

                                try
                                {
                                    new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundBill(ord.car_no, Convert.ToInt32(ord.pay_fee * 100), item.order_id, item.order_id, out request);
                                }
                                catch (Exception)
                                {
                                    WeChatParking.Core.LogHelper.Info("退款retry超时", "无感主动退款订单");
                                }
                                // new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundStatus(item.order_id, item.upRefundId, out request);

                            }
                        }
                    }//退款状态查询
                    else if (item.type == 3)
                    {
                        if (item.num <= 2)
                        {
                            if (item.time.AddSeconds(10) <= DateTime.Now)
                            {
                                var ord = new WeChatParking.Core.BLL.PrepaidOrder().GetOrder(item.order_id);
                                new WeChatParking.Core.BLL.retry().Update(item);
                                try
                                {
                                    new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundStatus(item.order_id, item.upRefundId, out request);
                                }
                                catch (Exception)
                                {
                                    WeChatParking.Core.LogHelper.Info("退款retry超时", "无感主动退款查询订单");
                                }
                            }
                        }
                    }
                    else if (item.type == 4)
                    {
                        if (item.num < 3)
                        {
                            if (item.time.AddMinutes(1) <= DateTime.Now)
                            {
                                new WeChatParking.Core.Payment.UnionPay.ActiveAct().payStatus(item.order_id, out request);
                                new WeChatParking.Core.BLL.retry().Update(item);
                            }
                        }
                    }
                }
            }
            return OK();
        }
        /// <summary>
        /// 开启服务
        /// </summary>
        /// <param name="iptxt"></param>
        /// <param name="Port"></param>
        /// <returns></returns>
        private string OpenServer(string iptxt, int Port)
        {
            if (iptxt.Length == 0 && Port == 0)
            {
                return "确保IP与端口正确";
            }
            openServer = new AsyncSocketTCPServer(IPAddress.Parse(iptxt), Port, 1024);
            try
            {
                openServer.Start();
                //接收数据
                openServer.DataReceived += openServer_DataReceived;
            }
            catch (Exception ex)
            {
                WeChatParking.Core.LogHelper.Error(ex, "TCP开启服务异常");
                return "开启服务出现未处理的异常：";
            }
            return "";
        }
        /// <summary>
        /// 接收的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openServer_DataReceived(object sender, AsyncSocketEventArgs e)
        {
            try
            {
                string IpAndPort = e._state.ClientSocket.RemoteEndPoint.ToString();
                byte[] buffer = e._state.RecvDataBuffer;
                string code = "";
                //接收数据后处理数据并发数据
                byte[] byteArray = SendDatas.beiDongSendData(IpAndPort, buffer, ref code);

                if (code.Length > 0)
                {
                    if (!DicListData.ContainsKey(code))
                    {
                        DicListData.Add(code, new SocketList() { soc = e._state.ClientSocket, time = DateTime.Now });
                    }
                    else
                    {
                        DicListData[code].time = DateTime.Now;
                    }
                }
                if (byteArray != null && e._state != null)
                {
                    openServer.Send(e._state, byteArray);
                }
            }
            catch (Exception ex)
            {
                WeChatParking.Core.LogHelper.Error(ex, "TCP接收的数据并处理");
            }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="dataByte"></param>
        /// <param name="code">客户端代码</param>
        /// <returns>发送成功</returns>
        public static bool Send(byte[] dataByte, string code)
        {
            if (dataByte != null && code.Length > 0)
            {
                if (DicListData.ContainsKey(code))
                {
                    if (DicListData[code] != null)
                    {
                        try
                        {
                            openServer.Send(DicListData[code].soc, dataByte);
                            return true;
                        }
                        catch (Exception)
                        {
                            DicListData[code].soc.Close();
                        }
                        finally
                        {
                            DicListData.Remove(code);
                        }

                    }
                }
            }
            return false;

        }
    }
}
